package com.lk.springboot.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lk.springboot.bean.Press;
import com.lk.springboot.dao.PressMapper;
import com.lk.springboot.dao.UsersMapper;
import com.lk.springboot.bean.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class UsersController {
    @Autowired
    UsersMapper usersMapper;

    @RequestMapping("/addUsers")
    public String listUsers(Users u) throws Exception {
        usersMapper.save(u);
        return "redirect:listUsers";
    }

    @RequestMapping("/deleteUsers")
    public String deleteUsers(Users u) throws Exception {
        usersMapper.delete(u.getU_id());
        return "redirect:listUsers";
    }

    @RequestMapping("/updateUsers")
    public String updateUsers(Users u) throws Exception {
        usersMapper.update(u);
        return "redirect:listUsers";
    }

    @RequestMapping("/listUsers")
    public String listUsers(Model m, @RequestParam(value = "start", defaultValue = "0") int start, @RequestParam(value = "size", defaultValue = "5") int size) throws Exception {
        PageHelper.startPage(start, size, "u_id desc");
        List<Users> cs = usersMapper.findAll();
        PageInfo<Users> page = new PageInfo<>(cs);
        m.addAttribute("page", page);
        return "listUsers";
    }

    @RequestMapping("/searchUser")
    public String searchList(Users u, Model m, @RequestParam(value = "start", defaultValue = "0") int start, @RequestParam(value = "size", defaultValue = "5") int size) throws Exception {
        PageHelper.startPage(start, size, "u_id desc");
        List<Users> cs = null;
        if (u.getU_name() != "") {
            cs = usersMapper.findByName(u.getU_name());
        } else if (u.getSex() != "") {
            cs = usersMapper.findBySex(u.getSex());
        } else if (u.getSex() == "" && u.getU_name() == "") {
            cs = usersMapper.findAll();
        }
        PageInfo<Users> page = new PageInfo<>(cs);
        m.addAttribute("page", page);
        return "listUsers";
    }


}
